<template>
  <!-- 移动弹窗 -->
    <!--<vue-draggable-resizable
        :w="150"
        :h="150"
        :x="50"
        :y="50"
        :min-width="400"
        :min-height="400"
        :parent="true"
        :grid="[10,10]"
        class-name="dragging1"
        @dragging="onDrag"
        @resizing="onResize"
      >-->
    <el-dialog title="移动至"
               :visible.sync="visible"
               width="30%"
               ref="moveDialog"
               :before-close="beforeClose"
               :modal="false"
               :close-on-click-modal="false"
               top="10%"
               class="treeBox"
               v-dialogDragCompletion>
      <el-tree v-if="visible"
               :props="treeprops"
               :load="loadNode"
               lazy
               ref="foldertree"
               node-key="name"
               :highlightCurrent="true">
        <div class="cus-tree-node"
             slot-scope="{ data }">
          <img :src="MY_URL['']" />
          <div v-if="data.isEdit"
               class="insnode">
            <el-input :ref="data.name"
                      v-model="data.label"
                      @blur="treeblur(data)"
                      @keyup.enter.native="$event.target.blur"></el-input>
          </div>
          <div v-else
               class="cusdisnode">
            <span>{{data.label}}</span>
            <!--<i v-if="data.etag == '' && node.expanded == false" class="el-icon-arrow-down"></i>
            <i v-if="data.etag == '' && node.expanded == true" class="el-icon-arrow-up"></i>-->
          </div>
        </div>
      </el-tree>
      <span slot="footer"
            style="height: 15%;">
        <el-button size="mini"
                   class="moveBtn"
                   @click="insFolder">新建文件夹</el-button>
        <div class="treedialogBtn">
          <el-button size="mini"
                     class="moveBtn"
                     @click="close">取消</el-button>
          <el-button size="mini"
                     class="moveBtn movesureBtn"
                     @click="submit">确定</el-button>
        </div>
      </span>
    </el-dialog>
    <!--</vue-draggable-resizable>-->
</template>

<script>
import {
  getListData,
  moveAjaxHandle,
  movedirAjaxHandle,
} from '@/apis/file';
import { api } from '@/utils/api';
import { MY_URL } from '@/utils/constants';

export default {
  data() {
    return {
      MY_URL,
      treeprops: {
        label: 'label',
        children: 'children',
      },
    };
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    beforeClose: {
      type: Function,
      default: () => {},
    },
    showList: {
      type: Array,
      default: () => [],
    },
  },
  watch: {
    visible(val) {
      if (val === false) {
        const el = this.$refs.moveDialog.$el.querySelector('.el-dialog');
        setTimeout(() => {
          el.style.height = '280px';
          el.style.width = '30%';
        }, 500);
      }
    },
  },
  methods: {
    close() {
      this.$emit('close');
    },
    submit() {
      this.moveFolder();
    },
    moveFolder() {
      // 若为当前目录下，则提示文件或文件夹已存在
      const issData = this.showList.filter((item) => item.isS);
      const currentNodedata = this.$refs.foldertree.getCurrentNode();
      if (currentNodedata == null) {
        this.$message({
          message: this.$t('no movefolder choice'),
        });
        return;
      }
      const currentNode = this.$refs.foldertree.getNode(currentNodedata);
      const exArr = []; // 选中已存在文件夹下
      const folArr = []; // 文件
      const dirArr = []; // 文件夹
      issData.forEach((item) => {
        let label = '';
        if (item.etag === '') {
          const namearr = item.name.split('/');
          label = namearr.splice(-1, 1).join('/');
        } else {
          const ind = item.name.lastIndexOf('/');
          label = `${item.name.slice(0, ind)}/`;
        }
        if (label === currentNode.data.name) { // 选中目录中name /前  == 移动到目录name
          exArr.push(item);
        } else {
          let objectDst = currentNode.data.name;
          const arrobjectSrc = item.name.split('/');
          if (item.etag === '') {
            objectDst += `${arrobjectSrc[arrobjectSrc.length - 2]}/`;
            const objectdata = { objectSrc: item.name, objectDst };
            dirArr.push(objectdata);
          } else {
            objectDst += arrobjectSrc[arrobjectSrc.length - 1];
            const objectdata = { objectSrc: item.name, objectDst };
            folArr.push(objectdata);
          }
        }
      });
      if (exArr.length > 0 && folArr.length === 0 && dirArr.length === 0) { // 文件或文件夹均存在该目录下
        this.$message.error(this.$t('moveto fail'));
        return;
      }
      // this.gridmenuDetet('move', data, currentNode).then(res => {})
      if (folArr.length > 0) {
        moveAjaxHandle(folArr).then((response) => {
          if (response.Code === 200) {
            if (response.Result.failed.length === 0) {
              // 删除移动的非该目录下
              // 这里需要emit到父组件处理
              // this.showList = this.showList.filter((item) =>
              // { return (!item.isS || (item.isS && exArr.indexOf(item.name) != -1)) })
              // this.movedialogVisible = false
              this.$message({
                type: 'success',
                message: this.$t('moveto folder', { msg: currentNode.data.label }),
              });
            } else {
              this.$message.error(this.$t('moveto fail'));
            }
            // 部分文件或文件夹存在该目录下
            // if(exArr.length > 0) {}
          }
        });
      }
      if (dirArr.length > 0) {
        movedirAjaxHandle(dirArr).then((response) => {
          if (response.Code === 200) {
            if (response.Result.failed.length === 0) {
              // 删除移动的非该目录下
              // 这里需要emit到父组件处理
              // this.showList = this.showList.filter(
              //  (item) => { return (!item.isS || (item.isS && exArr.indexOf(item.name) != -1)) })
              // this.movedialogVisible = false
              this.$message({
                type: 'success',
                message: this.$t('moveto folder', { msg: currentNode.data.label }),
              });
            } else {
              this.$message.error(this.$t('moveto fail'));
            }
          }
        });
      }
    },
    loadNode(node, resolve) {
      if (node.level === 0) {
        getListData('').then((data) => {
          let treelist = data;
          treelist = treelist.filter((item) => {
            const ind = item.name.lastIndexOf('/');
            const label = item.name.slice(0, ind);
            item.label = label;
            const mlflag = (label === '全部文件' || label === '相册' || label === '音乐' || label === '文档');
            return (item.etag === '' && mlflag);
          });
          return resolve(treelist);
        });
      } else {
        // etag为空表示非子节点
        if (node.data.name === '' || (node.data.etag && node.data.etag !== '')) { // 一新增文件夹，二为子节点
          return resolve([]);
        }
        api.list({ prefix: node.data.name, bucket: 'lion' }).then((response) => {
          if (response.Code === 200) {
            let data = response.Result;
            data = data.filter((item) => {
              const namearr = item.name.split('/');
              if (item.etag === '') {
                item.label = namearr[namearr.length - 2];
              } else {
                item.label = namearr[namearr.length - 1];
              }
              return item.etag === '';
            });
            if (data.length === 0) {
              this.$message({
                message: this.$t('treenode null'),
              });
            }
            return resolve(data);
          }
          return resolve();
        });
      }
      return resolve();
    },
    insFolder() {
      const currentNodedata = this.$refs.foldertree.getCurrentNode();
      if (currentNodedata == null) {
        this.$message({
          message: this.$t('moveto choice'),
        });
        return;
      }
      const currentNode = this.$refs.foldertree.getNode(currentNodedata);
      const data = currentNode.data.etag !== '' ? '/新建文件夹' : '新建文件夹';
      const newNode = {
        name: currentNode.data.name + data, label: '新建文件夹', isEdit: true, etag: '11',
      };
      this.$refs.foldertree.append(newNode, currentNode);
      const THIS = this;
      setTimeout(() => {
        THIS.$refs[`${newNode.name}`].focus();
      }, 50);
    },
    treeblur(data) {
      // this.$refs.foldertree.updateKeyChildren(data.label, data)
      // 请求新增接口，若为当前可视目录下，showList新增
      // api.list({prefix: node.data.name, bucket: 'lion'}).then((response)=>{
      // if (response.Code === 200) {
      /// /if(this) // showlist\前面 == data.name\前 为当前左侧文件下
      // }
      // })
      data.isEdit = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.cus-tree-node {
    .insnode {
      display: inline-block;
    }
    .cusdisnode {
      display: inline-block;
      span {
        display: inline-block;
        line-height: 28px;
      }
    }
    img {
      position: relative;
      width: 20px;
      height: 20px;
      top: 4px;
    }
}

.moveBtn {
  border-radius: 14px;
}

.movesureBtn {
  background: #2a66fa;
}

.treedialogBtn {
  display: inline-block;
  position: absolute;
  right: 20px;
}

</style>

<style lang="scss">
.treeBox {
    .el-dialog {
      height: 280px;
    }
    .el-dialog__body {
      height: calc(100% - 148px) !important;
    }
    .el-tree-node__content {
      height: 28px;
    }
    .el-input__inner {
      height: 28px;
      line-height: 28px;
    }
    .el-input,
    .el-tree-node__content {
      height: 30px;
    }
    .el-icon-caret-right:before {
      content: "";
    }
    .el-tree-node:focus > .el-tree-node__content,
    .el-tree-node__content:hover {
      background-color: #e2f2ff;
    }
    .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: #e2f2ff;
    }
    .el-tree-node__content > .el-tree-node__expand-icon {
      display: none;
    }
    .el-tree-node__loading-icon {
      display: none;
    }
    .el-dialog__footer {
      text-align: left;
      position: relative;
    }
    .el-dialog__body {
      height: 70%;
      overflow: auto;
    }
    .moveBtn:focus,
    .moveBtn:hover {
      background: none;
      border-color: #b6bcc3;
    }
    .movesureBtn:focus,
    .movesureBtn:hover {
      background: #2a66fa;
      border-color: #2a66fa;
    }
    .movesureBtn {
      border-color: #2a66fa;
      span {
        color: #ffffff;
      }
    }
  }
</style>
